<template>
  <div class="clue-management">
    <!-- 搜索区域和录入按钮 -->
    <div class="search-area">
      <el-button type="primary" @click="showAddDialog">+录入线索</el-button>
      <div class="search-inputs">
        <el-input
          v-model="searchParams.responsibleCadreid"
          placeholder="请输入负责干部编号"
          clearable
          style="width: 200px; margin-right: 10px;"
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>

    <!-- 线索表格 -->
    <el-table :data="pagedClues" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="clueId" label="线索编号" width="120" />
      <el-table-column prop="responsibleCadreid" label="负责干部编号" width="180" />
      <el-table-column prop="belongArea" label="所属辖区" width="250" />
      <el-table-column prop="riskType" label="风险类型" width="180" />
      <el-table-column prop="riskLevel" label="风险级别" width="100">
        <template #default="{ row }">
          <el-tag :type="row.riskLevel === 1 ? 'danger' : row.riskLevel === 2 ? 'warning' : 'info'">
            {{ row.riskLevel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="riskRemark" label="风险备注" />
      <el-table-column prop="isAssigned" label="是否分配" width="120">
        <template #default="{ row }">
          <el-tag :type="row.responsibleCadreid ? 'success' : 'info'">
            {{ row.responsibleCadreid ? '已分配' : '未分配' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button type="text" @click="showEditDialog(row)">修改</el-button>
          <el-button type="text" style="color: #f56c6c;" @click="handleDelete(row)">删除</el-button>
          <el-button type="text" @click="showAssignDialog(row)">分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :total="totalClues"
        :page-sizes="[5, 10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 录入线索对话框 -->
    <el-dialog
      title="录入线索"
      v-model="addDialogVisible"
      width="500px"
      :before-close="handleCloseAddDialog"
    >
      <el-form :model="clueForm" label-width="100px">
        <el-form-item label="贫困户id" required>
          <el-input v-model="clueForm.familyId" placeholder="请输入对应的贫困户id" />
        </el-form-item>
        <el-form-item label="省" required>
          <el-input v-model="clueForm.province" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="市" required>
          <el-input v-model="clueForm.city" placeholder="请输入市" />
        </el-form-item>
        <el-form-item label="县" required>
          <el-input v-model="clueForm.county" placeholder="请输入县" />
        </el-form-item>
        <el-form-item label="村" required>
          <el-input v-model="clueForm.village" placeholder="请输入村" />
        </el-form-item>
        <el-form-item label="风险类型" required>
          <el-checkbox-group v-model="clueForm.riskType">
            <el-checkbox v-for="type in riskTypes" :key="type" :label="type">{{ type }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="风险级别" required>
          <el-select v-model="clueForm.riskLevel" placeholder="请选择">
            <el-option label="1" value="1" />
            <el-option label="2" value="2" />
            <el-option label="3" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险备注">
          <el-input v-model="clueForm.riskRemark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseAddDialog">取消</el-button>
        <el-button type="primary" @click="handleAddConfirm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 修改线索对话框 -->
    <el-dialog
      title="修改线索"
      v-model="editDialogVisible"
      width="500px"
      :before-close="handleCloseEditDialog"
    >
      <el-form :model="clueForm" label-width="100px">
        <el-form-item label="省" required>
          <el-input v-model="clueForm.province" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="市" required>
          <el-input v-model="clueForm.city" placeholder="请输入市" />
        </el-form-item>
        <el-form-item label="县" required>
          <el-input v-model="clueForm.county" placeholder="请输入县" />
        </el-form-item>
        <el-form-item label="村" required>
          <el-input v-model="clueForm.village" placeholder="请输入村" />
        </el-form-item>
        <el-form-item label="风险类型" required>
          <el-checkbox-group v-model="clueForm.riskType">
            <el-checkbox v-for="type in riskTypes" :key="type" :label="type">{{ type }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="风险级别" required>
          <el-select v-model="clueForm.riskLevel" placeholder="请选择">
            <el-option label="1" value="1" />
            <el-option label="2" value="2" />
            <el-option label="3" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险备注">
          <el-input v-model="clueForm.riskRemark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseEditDialog">取消</el-button>
        <el-button type="primary" @click="handleEditConfirm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 分配线索对话框 -->
    <el-dialog
      title="分配线索"
      v-model="assignDialogVisible"
      width="600px"
      :before-close="handleCloseAssignDialog"
    >
      <el-input
        v-model="cadreSearch"
        placeholder="搜索负责干部编号或姓名"
        clearable
        style="width: 300px; margin-bottom: 20px;"
        @input="handleCadreSearch"
      />
      <el-table :data="pagedCadres" border style="width: 100%;">
        <el-table-column prop="cadreId" label="干部编号" min-width="150" />
        <el-table-column prop="name" label="干部姓名" min-width="150" />
        <el-table-column label="操作" min-width="120">
          <template #default="{ row }">
            <el-button type="text" @click="selectCadre(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;">
        <span v-if="selectedCadre" style="margin-right: 20px;">
          已选择: {{ selectedCadre.cadreName }} ({{ selectedCadre.cadreId }})
        </span>
      </div>
      <template #footer>
        <el-button @click="handleCloseAssignDialog">取消</el-button>
        <el-button type="primary" @click="handleAssignConfirm">确认分配</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {getClueTables,addClueTables,deleteClueTables ,updateClueTables,assignClueTables} from '@/api/city'
import { getCadreTables} from '@/api/admin'

const pagedClues = ref([])

    const currentPage = ref(1)
    const pageSize = ref(10)
    // 搜索参数
    const searchParams = reactive({
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      responsibleCadreid:''
    })
const totalClues = ref(0)
const queryClue = () => {
  getClueTables(searchParams).then((res) => {
    if (res.code == 2000) {
      pagedClues.value = res.data
      totalClues.value = res.total
    } else {
      pagedClues.value = []
      totalClues.value = 0
    }
})
}
queryClue()



    // 风险类型选项
    const riskTypes = ref([
      '因病返贫',
      '因学返贫',
      '因残返贫',
      '因自然灾害返贫',
      '因意外事故返贫',
      '因产业项目失败返贫',
      '因务工就业返贫',
      '缺劳动力',
      '其他'
    ])

    // 线索表单
    const clueForm = reactive({
      clueId: '',
      province: '',
      city: '',
      county: '',
      village: '',
      riskType: [],
      riskLevel: '',
      riskRemark: '',
      familyId:''
    })

    // 对话框状态
    const addDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const assignDialogVisible = ref(false)
    const currentClueId = ref('')

    const cadreSearch = ref('')
    const selectedCadre = ref(null)
    const currentAssignClue = ref(null)

    // 显示添加对话框
    const showAddDialog = () => {
      resetClueForm()
      addDialogVisible.value = true
    }

    // 显示编辑对话框
    const showEditDialog = (row) => {
      currentClueId.value = row.clueId
      Object.assign(clueForm, {
        clueId: row.clueId,
        province: row.province,
        city: row.city,
        county: row.county,
        village: row.village,
        riskType:row.riskType ? row.riskType.split(',') : [],
        riskLevel: row.riskLevel.toString(),
        riskRemark: row.riskRemark
      })
      editDialogVisible.value = true
    }

    // 显示分配对话框
    const showAssignDialog = (row) => {
      currentAssignClue.value = row
      selectedCadre.value = row.isAssigned 
        ? { cadreId: row.responsibleCadreId, cadreName: row.responsibleCadreName }
        : null
      cadreSearch.value = ''
      assignDialogVisible.value = true
    }

    // 重置线索表单
    const resetClueForm = () => {
      Object.assign(clueForm, {
        clueId: '',
        province: '',
        city: '',
        county: '',
        village: '',
        riskType: [],
        riskLevel: '',
        riskRemark: ''
      })
    }

    // 关闭添加对话框
    const handleCloseAddDialog = () => {
      addDialogVisible.value = false
    }

    // 关闭编辑对话框
    const handleCloseEditDialog = () => {
      editDialogVisible.value = false
    }

    // 关闭分配对话框
    const handleCloseAssignDialog = () => {
      assignDialogVisible.value = false
      selectedCadre.value = null
    }

    // 确认添加
    const handleAddConfirm = () => {
      // 验证表单
      if (!clueForm.province || !clueForm.city || !clueForm.county || !clueForm.village || 
          !clueForm.riskType.length || !clueForm.riskLevel) {
        ElMessage.warning('请填写完整信息')
        return
      } 
      // 创建新线索
      const newClue = {
        belongArea: `${clueForm.province}${clueForm.city}${clueForm.county}${clueForm.village}`,
        province: clueForm.province,
        city: clueForm.city,
        county: clueForm.county,
        village: clueForm.village,
        riskType: clueForm.riskType.join(',') ,
        riskLevel: parseInt(clueForm.riskLevel),
        riskRemark: clueForm.riskRemark || '无',
        isAssigned: false,
        responsibleCadreId: '',
        responsibleCadreName: '',
        familyId:clueForm.familyId
      }
      addClueTables(newClue).then(res => {
      if (res.code == 2000) {
        ElMessage.success('添加成功')
        handleSearch() // 重新筛选数据
      }
    })
      // 添加到线索列表
      // clues.value.unshift(newClue)
      // ElMessage.success('添加成功')
      // handleSearch() // 重新筛选数据
      addDialogVisible.value = false
    }

    // 确认修改线索
    const handleEditConfirm = () => {
      // 验证表单
      if (!clueForm.province || !clueForm.city || !clueForm.county || !clueForm.village || 
          !clueForm.riskType.length || !clueForm.riskLevel) {
        ElMessage.warning('请填写完整信息')
        return
      }
      // 更新线索
        const newUpdate= {
          clueId:clueForm.clueId,
          belongArea: `${clueForm.province}${clueForm.city}${clueForm.county}${clueForm.village}`,
          province: clueForm.province,
          city: clueForm.city,
          county: clueForm.county,
          village: clueForm.village,
          riskType: clueForm.riskType.join(',') ,
          riskLevel: parseInt(clueForm.riskLevel),
          riskRemark: clueForm.riskRemark || '无',
        }
        updateClueTables(newUpdate).then(res => {
        if (res.code == 2000) {
          ElMessage.success('修改成功')
          handleSearch() // 重新筛选数据
        }
      })
      editDialogVisible.value = false
    }

    // 处理删除
    const handleDelete = (row) => {
      ElMessageBox.confirm('是否确认删除该线索?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteClueTables(row.clueId).then(res => {
          ElMessage.success('删除成功')
          handleSearch() // 重新筛选数据
        })
        ElMessage.success('删除成功')
      }).catch(() => {
        // 取消删除
      })
    }

const pagedCadres = ref([])
const searchCadreParams = reactive({
  name: '',
  role: '村'
})
const totalCadre = ref(0)
const queryCadre = () => {
  getCadreTables(searchCadreParams).then((res) => {
    if (res.code == 2000) {
      pagedCadres.value = res.data
      totalCadre.value = res.total
    } else {
      pagedCadres.value = []
      totalCadre.value = 0
    }
  })
}
queryCadre()
    // 干部搜索
    const handleCadreSearch = () => {
      // 搜索逻辑已在filteredCadres计算属性中实现
    }

    // 选择干部
    const selectCadre = (cadre) => {
      selectedCadre.value = cadre
    }


    // 确认分配
    const handleAssignConfirm = () => {
      if (!selectedCadre.value) {
        ElMessage.warning('请选择负责干部')
        return
      }

      ElMessageBox.confirm(`是否确认将线索分配给 ${selectedCadre.value.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const assignparams={
          responsibleCadreid:selectedCadre.value.cadreId,
          clueId:currentAssignClue.value.clueId
        }
        assignClueTables(assignparams).then(res => {
        if (res.code == 2000) {
          ElMessage.success('分配成功')
          handleSearch() // 重新筛选数据
          assignDialogVisible.value=false
        }
      })
        const index = clues.value.findIndex(clue => clue.clueId === currentAssignClue.value.clueId)
        if (index !== -1) {
          clues.value[index] = {
            ...clues.value[index],
            isAssigned: true,
            responsibleCadreId: selectedCadre.value.cadreId,
            responsibleCadreName: selectedCadre.value.cadreName,
            updateTime: new Date().toLocaleString()
          }
          ElMessage.success('分配成功')
          handleSearch() // 重新筛选数据
        }
        assignDialogVisible.value = false
        selectedCadre.value = null
      }).catch(() => {
        // 取消分配
      })
    }

    // 处理搜索
    const handleSearch = () => {
      queryClue()
    }

    // 处理分页大小变化
    const handleSizeChange = (val) => {
      searchCadreParams.pageSize = val
      queryClue()
    }

    // 处理当前页变化
    const handleCurrentChange = (val) => {
      searchCadreParams.currentPage= val
      queryClue()
    }

    
</script>

<style scoped>
.clue-management {
  padding: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-inputs {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.el-button--text {
  padding: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-checkbox {
  margin-right: 15px;
  margin-left: 0;
}
</style>